package com.twb.easyExcel.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.twb.core.base.Result;
import com.twb.core.util.Results;
import com.twb.easyExcel.listener.EasyExcelListener;
import com.twb.easyExcel.service.IEasyExcelService;

/**
 * @ClassName EasyExcelReadUtil
 * @Description 读取excel的工具类
 * @author DHL
 * @date 2021年8月11日 上午10:18:42
 */
@SuppressWarnings("rawtypes")
public class EasyExcelReadUtil {
	
	protected static Logger log = LoggerFactory.getLogger(EasyExcelReadUtil.class);

	public static Result<String> easyRead(IEasyExcelService easyExcelService, String fileName, Class clazz, int headRowNumber, String errorFilePath) {
		try {
			if (headRowNumber < 0) {
				headRowNumber = 0;
			}
			
			ExcelReader excelReader = EasyExcel.read(fileName, clazz, new EasyExcelListener(easyExcelService)).build();
			
			ReadSheet readSheet = EasyExcel.readSheet(0).headRowNumber(headRowNumber).build();
			
			excelReader.read(readSheet);
			
			// 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
			excelReader.finish();
			
			return easyExcelService.finish(errorFilePath);
		} catch (Exception e) {
			log.error(easyExcelService.getTitle() + "读取excel异常", e);
			
			return Results.failure("服务器异常,请重新上传");
		}
	}
}
